<?php 
class PHPTree{

	public static function getTree($array, $adds = false, $pid = 0, $hyphen = '', $nbsp = '') {
		$i = 0;
		$tree = array();
		$tmp = array();
		if($array){
			// $pid = 0;
			foreach($array as $key => $value) {
				if($value['parent_id'] == $pid) {
					$tree[$i] = $value;
					
					if($adds){
						$tree[$i]['adds'] = $nbsp . $hyphen;
						$tmp = self::getTree($array, $adds, $value['id'], '└─', $nbsp.'&nbsp;&nbsp;&nbsp;&nbsp;'); 
					}else{
						$tmp = self::getTree($array, $adds, $value['id']); 
					}
					if(!empty($tmp)) {
						$tree[$i]['children'] = $tmp;
						$tmp = array();
					}
					$i++;
				}
			}
		}
		return $tree;
	}

	
	public static function getTreeForHtml($array, $pid = 0, $lv = 0, $hyphen = '', $nbsp = '')
	{
	    static $tree = [];
	    foreach ($array as $v) {
	    	if($v['parent_id'] == $pid) {
	            $v['lv'] == $lv;
	            $v['adds'] = $nbsp . $hyphen;
	            $tree[]     = $v;
	            self::getTreeForHtml($array, $v['id'], $v['lv'] + 1, '└─', $nbsp.'&nbsp;&nbsp;&nbsp;&nbsp;');
	        }
	    }

	    return $tree;
	}


	public static function getTreeForAuth($array, $ids)
    {
    	$accessIds = explode(',',$ids);
    	$tree = self::getTree($array);
    	$authTree = self::getTreeForAuthArr($tree,$accessIds);
        return $authTree;
    }

    public static function getTreeForAuthArr($array, $accessIds)
    {
        foreach ($array as $key => $val) {
            $val['auth'] = in_array($val['id'], $accessIds);
            
            if($val['children']){
            	$val['children'] = self::getTreeForAuthArr($val['children'], $accessIds);
            }
            $tree[] = $val;
        }
        return $tree;
    }

    public static function getArrName($array,$name='name')
    {
    	$result = self::getTree($array,true);
        foreach ($result as $key => $val) {
            $v[$val['id']]['id'] = $val['id'];
            $v[$val['id']][$name] = $val[$name];
        }
        $res = $v;
        return $res;
	}
	
	public static function getTreeLable($array, $adds = false, $pid = 0, $hyphen = '', $nbsp = '') {
		$i = 0;
		$tree = array();
		$tmp = array();
		if($array){
			// $pid = 0;
			foreach($array as $key => $value) {
				if($value['parent_id'] == $pid) {
					$tree[$i]['value'] = $value['id'];
					$tree[$i]['label'] = $value['name'];

					$tmp = self::getTreeLable($array, $adds, $value['id']);
					if(!empty($tmp)) {
						$tree[$i]['children'] = $tmp;
						$tmp = array();
					}
					$i++;
				}
			}
		}
		return $tree;
	}
	
	
}